package com.dc.product.service.impl;

import com.dc.base.BaseApiService;
import com.dc.base.BaseResponse;
import com.dc.core.bean.DCBeanUtils;
import com.dc.product.es.entity.ProductEntity;
import com.dc.product.es.respository.ProductRepository;
import com.dc.product.service.IProductSerachService;
import com.dc.products.dto.ProductDto;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ProductSearchServiceImpl extends BaseApiService<List<ProductDto>> implements IProductSerachService {

    @Autowired
    private ProductRepository productRepository;

    @Override
    public BaseResponse<List<ProductDto>> search(@RequestParam("name") String name) {
        //1、拼接查询条件
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        //2、模糊查询
        builder.must(QueryBuilders.fuzzyQuery("name", name));
        //builder.must(QueryBuilders.multiMatchQuery(name,"name","subtitle","detail"));  多个字段都进行查询
        Pageable pageable = new QPageRequest(0, 5);   //接口传入
        //3、调用ES接口查询
        Page<ProductEntity> page = productRepository.search(builder, pageable);
        //4、获取集合数据
        List<ProductEntity> content = page.getContent();
        //5、将 entity 转换成 dto
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<ProductDto> mapAsList = mapperFactory.getMapperFacade().mapAsList(content, ProductDto.class);
        ProductDto productDto = DCBeanUtils.doToDto(content, ProductDto.class);
        return setResultSuccess(mapAsList + "--" + productDto);
    }
}
